package com.cljh.controller;

import com.cljh.bean.Admin;
import com.cljh.bean.Saler;
import com.cljh.config.AuthAccess;
import com.cljh.controller.page.*;
import com.cljh.service.AdminService;
import com.cljh.service.SalerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
@RestController
@RequestMapping("/salers")
public class SalerController {

    @Autowired
    SalerService salerService;

    //注册
    @AuthAccess
    @PostMapping("/register/{code}")
    public Result register(@RequestBody AdminSaler admin, HttpServletRequest request, @PathVariable String code){
        //大写
        code=code.toUpperCase(Locale.ROOT);
        System.out.println(code);

        //获取servletContext上下文对象
        String servletContext = (String) request.getServletContext().getAttribute("code");
        System.out.println("servletContext="+servletContext);
        if (!code.equals(servletContext)){
            return new Result(Code.SAVE_ERR,false,"验证码错误");
        }

       boolean save= salerService.save(admin);


        Integer c = save ? Code.SAVE_OK : Code.SAVE_ERR;
        String msg = save ? "注册成功" : "注册失败";
        return new Result(c, save, msg);
    }


    @AuthAccess
    @PostMapping("/{pn}/{size}")
    public Result selectProduct(@PathVariable(value = "pn") Integer pn, @PathVariable(value = "size")Integer size,@RequestBody Admin admin){
        System.out.println(admin);
        PageBean<Saler> salerPageBean =  salerService.selectAllByCondition(pn, size, admin);
        Integer code=salerPageBean !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=salerPageBean!=null ? "查询到信息":"未查询到信息";
        return new Result(code,salerPageBean,msg);
    }

    @GetMapping("/{id}")
    public Result selectByAdminId(@PathVariable Integer id){
        Saler saler=salerService.selectByAdminId(id);
        Integer code=saler !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=saler!=null ? "查询到信息":"未查询到信息";
        return new Result(code,saler,msg);
    }

    @PutMapping
    public Result upd(@RequestBody Saler saler){
        boolean update = salerService.upd(saler);
        Integer code=update ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg=update ? "修改成功":"修改失败";
        return new Result(code,update,msg);
    }
}
